import * as MqClient from './MqClient.js';
import * as WebRtc from './WebRtc.js';

let ctiConfig = { 
   MQTT_SERVICE:'',
   companyCode:'',
   agentno:'',
   password:'',
   pstnnumber:'',
   WEBRTC_SERVICE:'',
   exten:'',
   phoneType:'0',
   agentState:'-1',
   handUpStatus:'1',
   popupUrl:'',
};
let mqDestination;
let agentstatus;
let heartbeatId;  //心跳标识

let userIp;  //用户的ip
let signinFlag = false;  //登录标识
let reconnection;  //重连标识
let timeoutFlag;  //签入超时标识，默认30s超时
let loseHeartbeat = 0;  //未接收到心跳的次数
let timeoutSec = 10;  //心跳时间，单位s
let WEBRTC_ADDRESS = ''
let MQTT_ADDRESS = ''
// 定义window级别发送方法
window['sendMessage'] = (method,val) =>{
   sendMessage(method,val);
 }
/**
 * 签入或签出,
 * @param {*} paramsConfig 
 */
export function ctiSignInOrOut(paramsConfig,val){
   ctiConfig = paramsConfig;
   mqDestination = "/queue/" + ctiConfig.companyCode + "_" + ctiConfig.agentno;
   if(heartbeatId>=0){
      clearInterval(heartbeatId);
   }
   if(!signinFlag){
      // 连接前先调用mpcc接口，将登录中的座席强制签出 
      let param = {
         "agentNumber":ctiConfig.agentno,
         "companyCode":ctiConfig.companyCode
      }
      var httpRequest = new XMLHttpRequest(); 
      var postUrl = "http://"+ctiConfig.WEBRTC_SERVICE;
      if(ctiConfig.MQTT_SERVICE.indexOf('wss') != -1){
         postUrl = "https://"+ctiConfig.WEBRTC_SERVICE;
      }
      //此接口用于验证是否重复签入
      httpRequest.open('POST', postUrl+'/mpccApi/login/doCheckAgentStatus.json', true); 
      httpRequest.setRequestHeader("Content-type", "application/json");
      httpRequest.send(JSON.stringify(param)); //发送请求 将json写入send中
      httpRequest.onreadystatechange = function () { //请求后的回调接口，可将请求成功后要执行的程序写在其中
         if (httpRequest.readyState == 4 && httpRequest.status == 200) { //验证请求是否发送成功
            var res = JSON.parse(httpRequest.responseText);
            let result=res.flag;
            clearInterval(reconnection);
            if(result!="666"){
               this.$Modal.info({
                  title:'提示',
                  content:res.msg
               });
            return false;
            }
            
            let agentStatus = res.obj.agentStatus;
            userIp = res.obj.clientIp;
              if("-1" != agentStatus && loseHeartbeat<3){
                 var msg = "当前座席号已被签入，是否继续签入操作？"; 
                if (confirm(msg)==true){ 
                  doSignin(postUrl,param);
                   return;
               }else{
                  clearInterval(reconnection);
                  return;
               }
              }else{
                 doSignin(postUrl,param,val);
              }
            return;
         }
         if (httpRequest.status != 200) {
            console.info("签入获取座席状态失败！");
            // alert("签入获取座席状态失败！");
            reconnection = setInterval(function(){
                                  refreshSign();
                               },30000)
         }

      };
   }else{
      // displayLoadingMessage();
      sendMessage('signout');
   }
}

function refreshSign(val) {
   clearInterval(reconnection);
   signinFlag = false;
   console.info("正在进行重连，请稍后");
   WebRtc.unRegested(); // 重连先取消注册
   paramConfig.agentno = localStorage.getItem('agentno');
   paramConfig.password = localStorage.getItem('password');
   paramConfig.exten = localStorage.getItem('exten');
   ctiSignInOrOut(paramConfig, val);
}
function doSignin(postUrl,param,val){
   if (val == '8') param.isAbnormalReconnection = '1';
   var httpRequestOne = new XMLHttpRequest(); 
   httpRequestOne.open('POST', postUrl+'/mpccApi/login/doAgentStatus.json', true); 
   httpRequestOne.setRequestHeader("Content-type", "application/json");
   httpRequestOne.send(JSON.stringify(param)); //发送请求 将json写入send中

   /**
    * 获取数据后的处理程序
    */
   httpRequestOne.onreadystatechange = function () { //请求后的回调接口，可将请求成功后要执行的程序写在其中
      if (httpRequestOne.readyState == 4 && httpRequestOne.status == 200) { //验证请求是否发送成功
         var res = JSON.parse(httpRequestOne.responseText);
         let result=res.flag;
         if(result!="666"){
            that.$Modal.info({
               title:'提示',
               content:res.msg
            });
         return false;
         }
         localStorage.setItem('minitorMenu',res.obj.minitorMenu)
         localStorage.setItem('skillGroup',JSON.stringify(res.obj.skillGroup));
         localStorage.setItem('customBusyStatusList',res.obj.customBusyStatusList ? res.obj.customBusyStatusList : '');
         localStorage.setItem('deptList',JSON.stringify(res.obj.deptList));
         localStorage.setItem('deptNameList',JSON.stringify(res.obj.deptNameList));
         localStorage.setItem('haveAi',res.obj.isAiAssistant);
         localStorage.setItem('haveVideo',res.obj.isSupportVideo);
         localStorage.setItem('afterDoTime',res.obj.afterDoTime);  //后处理时长
         // 获取mq,webrtc地址
         doMqAndWebRtcInfo(postUrl);
      }
   };
}
// 动态获取mq,webrtc地址
function doMqAndWebRtcInfo(postUrl) {
   let param={
      companyCode: ctiConfig.companyCode
   };
   let that = this;
   var httpRequestOne = new XMLHttpRequest(); 
   httpRequestOne.open('POST', postUrl+'/mpccApi/login/doMqAndWebRtcInfo.json', true); 
   httpRequestOne.setRequestHeader("Content-type", "application/json");
   httpRequestOne.send(JSON.stringify(param)); //发送请求 将json写入send中
   /**
    * 获取数据后的处理程序
    */
   httpRequestOne.onreadystatechange = function () { //请求后的回调接口，可将请求成功后要执行的程序写在其中
      if (httpRequestOne.readyState == 4 && httpRequestOne.status == 200) { //验证请求是否发送成功
         var res = JSON.parse(httpRequestOne.responseText);
         let result=res.flag;
         if(result!="666"){
            that.$Modal.info({
               title:'提示',
               content:res.msg
            });
            return false;
         }
         var mqAddressItem = res.obj.mqInfo.find(item => item.configKey == 'mq_address')
         var registeredAddressItem = res.obj.webrtcInfo.find(item => item.configKey == 'registered_address')
         if (registeredAddressItem) {
            if (registeredAddressItem.configValue.indexOf(',') != -1) {
               registeredAddressItem.configValue = registeredAddressItem.configValue.replace(',','');
            }
            WEBRTC_ADDRESS = registeredAddressItem.configValue
         }
         if (paramConfig.MQTT_SERVICE.indexOf('wss') != -1) {
            if (mqAddressItem) {
               MQTT_ADDRESS = 'wss://'+ mqAddressItem.configValue +':15675/ws'
            }
         } else {
            if (mqAddressItem) {
               MQTT_ADDRESS = 'ws://'+ mqAddressItem.configValue +':15674/ws'
            }
         }
         // 签入时连接mq
			MqClient.connect(MQTT_ADDRESS,mqDestination);
			// 绑定队列连接webrtc
         setTimeout(()=>{
            connectFunction();
         },1000)
      }
   }
}
// 绑定队列连接webrtc
function connectFunction() {
   let param={
      companyCode: ctiConfig.companyCode,
      agentNumber: ctiConfig.agentno
   };
   let that = this;
   var postUrl = "http://"+WEBRTC_ADDRESS;
   if(ctiConfig.MQTT_SERVICE.indexOf('wss') != -1){
      postUrl = "https://"+WEBRTC_ADDRESS;
   }
   var httpRequestOne = new XMLHttpRequest(); 
   httpRequestOne.open('POST', postUrl+'/mpccApi/login/doQueueBinding.json', true); 
   httpRequestOne.setRequestHeader("Content-type", "application/json");
   httpRequestOne.send(JSON.stringify(param)); //发送请求 将json写入send中
   /**
      * 获取数据后的处理程序
      */
   httpRequestOne.onreadystatechange = function () {
      if (httpRequestOne.readyState == 4 && httpRequestOne.status == 200) { //验证请求是否发送成功
         var res = JSON.parse(httpRequestOne.responseText);
         let result=res.flag;
         if(result!="666"){
            that.$Modal.info({
               title:'提示',
               content:res.msg
            });
            return false;
         }
      }
   }
   setTimeout(function(){
      if(ctiConfig.phoneType != '0'){  //如果是外置，不进行注册 0-外置电话 1-内置
         WebRtc.register(ctiConfig.exten, ctiConfig.agentno,ctiConfig.password,WEBRTC_ADDRESS,MQTT_ADDRESS);
      }else{
         sendMessage('signin','');
      }
      // displayLoadingMessage();
      timeoutFlag = setTimeout(timeout,30000);  //签入，30s无响应超时
   },2000);
}
//请求超时
function timeout(){
   // hideLoadingMessage();
   signinFlag = false;
   setToolbarByStatus('-1');
   if(heartbeatId){
      clearInterval(heartbeatId);
   }
   // 签出注销分机
   WebRtc.unRegested();
   MqClient.disconnect();
   console.warn("与服务器连接中断，正在重新签入");
   paramConfig.agentno = localStorage.getItem('agentno');
   paramConfig.password = localStorage.getItem('password');
   paramConfig.exten = localStorage.getItem('exten');
   ctiSignInOrOut(paramConfig);
}

export function sendMessage(method,callee,param) {
   if(!param){
      param = "";
   }
   let message = "{'method':'"+method+"','callee':'"+callee+"','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+
         "','exten':'"+ctiConfig.exten+"','agentstatus':'"+agentstatus+"','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"'}";
   switch(method){
      case 'signin':
      case 'signout':
         message = "{'param1':'"+userIp+"','method':'"+method+"','callee':'"+callee+"','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+
      "','exten':'"+ctiConfig.exten+"','agentstatus':'0','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"'}";
         break;
      case 'get_queue_list': //获取技能组
         message = "{'method':'get_queue_list','agentno':'"+ctiConfig.agentno+"','companyCode':'"+ctiConfig.companyCode+"'}";
         break;
      case 'heartbeat':
         message = "{'method':'heartbeat','callee':'0','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+"','exten':'"+ctiConfig.exten+"','agentstatus':'0','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"','versionNo':'"+ctiConfig.versionNo+"'}";
         break;
      case 'get_customer_of_queue':
         message = "{'method':'get_customer_of_queue','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+"','exten':'"+ctiConfig.exten+"','agentstatus':'0','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"','queueNumLstStr':'"+callee+"'"+param+"}";
         break;
      case 'get_agents_monitor_info':
         message = "{'method':'get_agents_monitor_info','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+"','exten':'"+ctiConfig.exten+"','agentstatus':'1','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"','queueNumLstStr':'"+callee+"'}";
         break;
      case 'manual_callout':
         message = "{'method':'manual_callout','callee':'"+callee+"','agentno':'"+ctiConfig.agentno+"','password':'"+ctiConfig.password+"','exten':'"+ctiConfig.exten+"','pstnnumber':'"+ctiConfig.pstnnumber+"','companyCode':'"+ctiConfig.companyCode+"','cusData':'','param1':'externalApi'}";
         break;
      case 'change_status':
         message = "{'method':'change_status','agentno':'" + ctiConfig.agentno + "','password':'" + ctiConfig.password + "','exten':'" + ctiConfig.exten + "','agentstatus':'" + callee + "','pstnnumber':'" + ctiConfig.pstnnumber + "','companyCode':'" + ctiConfig.companyCode + "','timestamp':'"+ new Date()+ "' }";
         break;
      case 'internal_call':
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'internal_call','agentno':'"+ctiConfig.agentno+"','callee':'"+callee+"'}";
         break;
      case 'consult_transfer': //确定询问
         message = "{'companyCode':'" + ctiConfig.companyCode + "','method':'consult_transfer','agentno':'" + ctiConfig.agentno + "','pstnnumber':'" + ctiConfig.pstnnumber  + "','timestamp':'"+ new Date()+ "' }";
         break;
      case 'consult_cancel': //取消询问
         message = "{'companyCode':'" + ctiConfig.companyCode + "','method':'consult_cancel','agentno':'" + ctiConfig.agentno + "','pstnnumber':'" + ctiConfig.pstnnumber  + "','timestamp':'"+ new Date()+ "' }";
         break;
      case 'blind_transfer': //转接座席
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'blind_transfer','agentno':'"+ctiConfig.agentno+"','callee':'"+callee+"','pstnnumber':'"+ctiConfig.pstnnumber+"'}";
         break;
      case 'transfer_queue'://转接技能组
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'transfer_queue','agentno':'"+ctiConfig.agentno+"','queueNum':'"+callee+"','pstnnumber':'"+ctiConfig.pstnnumber+"'}";
         break;
      case 'transfer_ivr': //转接ivr
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'transfer_ivr','agentno':'"+ctiConfig.agentno+"','ivrNum':'"+callee+"','pstnnumber':'"+ctiConfig.pstnnumber+"'}";
         break;
      case 'set_acs_type':// 挂断后处理状态
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'set_acs_type','agentno':'"+ctiConfig.agentno+"','agentstatus':'"+callee+"'}";
         break;
      case 'consult': //询问
         message = "{'companyCode':'"+ctiConfig.companyCode+"','method':'consult','agentno':'"+ctiConfig.agentno+"','callee':'"+callee+"','pstnnumber':'"+ctiConfig.pstnnumber+"'}";
         break;
      case 'blind_outbound': //转接外线
         message = "{'companyCode':'" + ctiConfig.companyCode + "','method':'blind_outbound','agentno':'" + ctiConfig.agentno + "','callee':'" + callee + "','pstnnumber':'" + ctiConfig.pstnnumber + "','timestamp':'"+ new Date()+ "' }";
         break;
      case 'conf_stop'://结束
         break;
      case 'conf_invite'://邀请
         message = "{'companyCode':'" + ctiConfig.companyCode + "','method':'conf_invite','agentno':'" + ctiConfig.agentno + "','callee':'" + callee + "','pstnnumber':'" + ctiConfig.pstnnumber + "','timestamp':'"+ new Date()+ "' }";
         break;
      case 'conf_mute'://静音
      case 'conf_unmute':// 取消静音
      case 'conf_kickoff': //移除
         message = "{'companyCode':'" + ctiConfig.companyCode + "','method':'"+method+"','agentno':'" + ctiConfig.agentno + "','param2':'" + callee + "','timestamp':'"+ new Date()+ "' }";
         break;
   }

   MqClient.sendMsg(message);
}

/**
 * 处理从mq返回的消息
 * @param {*} eventType 事件类型 
 * @param {*} state 座席状态
 * @param {*} methodType 请求(返回)类型
 * @param {*} code 返回码
 * @param {*} jsonStr 返回数据
 */
 export function onEvent(eventType,state,methodType,code,jsonStr){
   if(eventType=='event'){
         switch(methodType){
            case 'signin':
               // 取消超时
               clearTimeout(timeoutFlag);
               if(code=='0'){
                  // 获取座席权限
                  sendMessage('get_defined_role_rights');
                  alert("签入成功");
                  setToolbarByStatus('0');
                  loseHeartbeat = 0;
                  clearInterval(reconnection);
                  signinFlag = true;
                  
                  if(heartbeatId){
                     clearInterval(heartbeatId);
                  }
                  heartbeatId = setInterval(heartbeat,timeoutSec*1000);

                  sendMessage('set_acs_type',ctiConfig.handUpStatus);//通话结束后座席状态默认空闲

                  sendMessage('get_accessnum_of_agent');//获取座席接入号
                 

               }else if(code=='-53'){
                  alert("登陆密码错误");
               }else{
                  alert("签入失败[ErrorCode:"+code+"]");
               }
               break;
            case 'disconnect':
            case 'signout':
               if(!signinFlag){
                  return;
               }
               clearTimeout(timeoutFlag);
	  			// hideLoadingMessage();
               if(jsonStr.reason == '3'){
                  alert("当前座席已在其他地方签入，请确认后继续操作");
               }
               signinFlag = false;
               setToolbarByStatus('-1');
               // 签出注销分机
               WebRtc.unRegested();
               MqClient.disconnect();
               
               alert("签出成功");
               
               break;
            case 'unhold_result':
               if (duofanging || conferenceFlag) {
                    unholdFlag = true;
                }
               break;
            case 'agent_status_change':
            case 'manual_callout_customer_ring':
            case 'manual_callout_customer_answer':
               if(jsonStr.agentno == ctiConfig.agentno){
                  setToolbarByStatus(state,methodType);
               }
               break;
            case 'common_callin_bridge_ring': //呼入弹屏
               if(jsonStr.agentno == ctiConfig.agentno){
                  customerPhoneFlag = true;
                  window.open(ctiConfig.popupUrl+"?phone="+jsonStr.customerNum+"&agentno="+jsonStr.agentno+"&companyCode="+ctiConfig.companyCode+"&agentUuid="+jsonStr.agentUuid,'_blank');
               }
               break;
            case 'manual_callout_agent_ring': //呼出弹屏
               if(jsonStr.agentno == ctiConfig.agentno){
                  customerPhoneFlag = true;
                  window.open(ctiConfig.popupUrl+"?phone="+jsonStr.customerNum+"&agentno="+jsonStr.agentno+"&companyCode="+ctiConfig.companyCode+"&agentUuid="+jsonStr.agentUuid,'_blank');
               }
               break;
            case 'internal_call_called_ring': // 坐席被叫振铃
               if(jsonStr.agentno == ctiConfig.agentno){
                  customerPhoneFlag = false;
               }
               break;
            case 'force_hangup_ring': //强拆振铃
               if(jsonStr.agentno == ctiConfig.agentno){
                  customerPhoneFlag = true;
               }
               break;
            case 'blind_transfer_ring':
            case 'consult_ring': //座席盲转被叫振铃及弹屏
               if(jsonStr.agentno == ctiConfig.agentno){
                  customerPhoneFlag = true;
                  window.open(ctiConfig.popupUrl+"?phone="+jsonStr.customerNum+"&agentno="+jsonStr.agentno+"&companyCode="+ctiConfig.companyCode+"&agentUuid="+jsonStr.agentUuid,'_blank');
               }
               break;
            case 'get_accessnum_of_agent': //获取座席接入号
               if(jsonStr.agentno == ctiConfig.agentno){
               }
               break;
            case 'get_info_of_agent':// 获取系统座席信息
            case 'get_queue_list': // 获取技能组信息
            case 'get_info_of_skill'://
            case 'get_info_of_ivr'://
               if(jsonStr.agentno == ctiConfig.agentno){
                  getInfo(jsonStr);
               }
               break;
            
            case 'conf_create_result': //多方创建会议返回
            case 'conference_ring'://多方被叫振铃
            case 'conf_stop_result'://多方发送结束命令
            case 'conf_destroy'://多方发送结束命令
            case 'enter_conf'://多方进入会议
            case 'leave_conf'://多方离开会议
            case 'conf_invite_result'://多方邀请参加返回
            case 'conf_invitee_hangup'://多方邀请被叫忙或拒接
               if (methodType == 'conference_ring') {
                  if (jsonStr.agentno == ctiConfig.agentno) {
                     customerPhoneFlag = false;
                     conferenceRingFlag = true;
                     conferenceFlag = true;
                  }
               } else {
                  conferenceRingFlag = false;
                  conferenceFlag = false;
                  unholdFlag = false;
               }
               confOperate(methodType,jsonStr);
               break;
            case 'hangup':
               customerPhoneFlag = false;
               break;
            case 'answer':
               if("CTI_CALL_TYPE_COMMON_CALL_IN" == jsonStr.callType){
                  if (conferenceRingFlag) {
                     customerPhoneFlag = false
                  } else {
                     customerPhoneFlag = true
                  }
                  conferenceRingFlag = false;
               }
               break;
            case 'get_customer_of_queue':
               let requestID = jsonStr.requestID;
                if(requestID){ //有值说明是从页面右上角切换
                  getSkillInfo(jsonStr);
                }else{  //无值说明是监控页面
                  openWindowSkill.monitorSkillData(jsonStr);
                }
               
               break;
            case 'get_agents_monitor_info':
               openWindowAgent.monitorSeatData(jsonStr);
               break;

         }
   }else if(eventType=='response'){
      switch(methodType){
         case 'signin':
            clearTimeout(timeoutFlag);
				// hideLoadingMessage();
				if(code=='0'){ //签入成功
					return false;
				}
				// 签入失败 注销分机
				WebRtc.unRegested();
				MqClient.disconnect();
				if(code=='-6'){
  					alert("请不要重复签入");
  				}else if(code=='-11'){
  					alert("分机不在线，签入失败");
  				}else if(code=='-12'){
  					alert("分机已被其他座席绑定，签入失败");
  				}else{
  					alert("签入失败[ErrorCode:"+code+"]");
				}
            break;
         case 'signout':
            if(jsonStr.reason == "3" && jsonStr.retCode == "0"){
               alert("当前座席号已在其他地方签入，请确认后继续操作");
               clearTimeout(timeoutFlag);
               // hideLoadingMessage();
               signinFlag = false;
               if(heartbeatId){
                  clearInterval(heartbeatId);
               }
               // if(changeStatusId){
               //    clearInterval(changeStatusId);
               // }
               // isChangeStatus("0");
               setToolbarByStatus('-1');
               // clearInterval(queueChangeId);
               // 签出注销分机
               WebRtc.unRegested();
               MqClient.disconnect();
               alert("签出成功");
            }
            break;
         case 'manual_callout':  //外呼
            if(code=='-19' || code=='-22'){
					alert("接入号不正确，呼叫失败");
				}else if(code=='-24' || code=='-31'){
					alert("座席非空闲状态，呼叫失败");
				}else if(code!='0'){
					alert("呼叫失败[ErrorCode:"+code+"]");
				}
            break;
         case 'internal_call': //内呼
            if(code=='-30'){
               alert("被叫座席不在线，呼叫失败");
            }else if(code=='-24' || code=='-31'){
               alert("座席非空闲状态，呼叫失败");
            }else if(code!='0'){
               alert("呼叫失败[ErrorCode:"+code+"]");
            }
            break;
         case 'blind_transfer': //转接座席
            if(code=='-30'){
               alert("被叫座席不在线，呼叫失败");
            }else if(code=='-24' || code=='-31' || code=='-32'){
               alert("座席非空闲状态，呼叫失败");
            }else if(code!='0'){
               alert("呼叫失败[ErrorCode:"+code+"]");
            }
            break;
         case 'blind_outbound': //转接外线
            if(code!='0'){
               alert("呼叫失败[ErrorCode:"+code+"]");
            }
            break;
         case 'threeway': //三方
            if(code=='-30'){
               alert("被叫座席不在线，呼叫失败");
            }else if(code=='-24' || code=='-31' || code=='-32'){
               alert("座席非空闲状态，呼叫失败");
            }else if(code!='0'){
               alert("呼叫失败[ErrorCode:"+code+"]");
            }
            break;
         case 'threeway_outbound': //三方外线
            if(code!='0'){
               alert("呼叫失败[ErrorCode:"+code+"]");
            }
            break;
         case 'heartbeat': //心跳检测
            if(code=='0'){
               loseHeartbeat = 0;
            }
            break;
         case 'ai_assistant_msg':  //ai助手
         if(jsonStr.event.data){
            let param={
              data:jsonStr.event.data,
              index:jsonStr.event.index,
              direction:jsonStr.msgFlag,
              agentNo:ctiConfig.agentno,
              name: ctiConfig.agentno,
              time:jsonStr.event.timestamp,
              customPhone:jsonStr.customerPhone
            }
            // if(ctiConfig.phoneType == '1' || ctiConfig.phoneType == '2'){
                 initAiContent(param);
//             }
          }
            break;
      }
   }else if(eventType=='redirectSign') {
      if(WebRtc.socket) {
         WebRtc.socket.disconnect();
      }
      WebRtc.unRegested();
      MqClient.disconnect();
      var postUrl = "http://"+WEBRTC_ADDRESS;
      if(ctiConfig.MQTT_SERVICE.indexOf('wss') != -1){
         postUrl = "https://"+WEBRTC_ADDRESS;
      }
      doMqAndWebRtcInfo(postUrl);
   }else{
      //技能组信息
      if(jsonStr.type == 'pushSkillGroupEvent'){
         getSkillInfo('pushSkillGroupEvent',jsonStr);
      }
   }
}
/**
 * 心跳
 */
function heartbeat(){
		if(loseHeartbeat > 4){
			signinFlag = false;
			if(heartbeatId){
				clearInterval(heartbeatId);
			}
			setToolbarByStatus('-1');
			// 签出注销分机
			WebRtc.unRegested();
			MqClient.disconnect();
			console.warn("心跳超时,座席即将重连...");
			reconnection = setInterval(function(){
                     refreshSign('8');
            },30000);
		}else{
			loseHeartbeat = loseHeartbeat + 1;
         // 心跳
         sendMessage('heartbeat');
         // 与心跳定时时间一致，10s获取一次技能组
         skillchange();
  		}
}

/**
 * 应答
 */
export function answer(){
   WebRtc.sipAnswer();
}
/**
 * 挂断
 */
export function hangUp(){
   WebRtc.hangUp();
}

export function refreshPage(){
   // 签出注销分机
   sendMessage('signout');
   if(ctiConfig.phoneType != 0){ //外置不进行注销
      WebRtc.unRegested();
   }
   
}

// 发送dtmf
export function sendDtmf(value){
   WebRtc.sendDtmf(value);
}

